package com.lizhi.note.controller;

import com.lizhi.note.config.provider.CustomUser;
import com.lizhi.note.dto.NotebookDTO;
import com.lizhi.note.dto.NotepageDTO;
import com.lizhi.note.payload.ApiResponse;
import com.lizhi.note.payload.ResponseUtil;
import com.lizhi.note.service.NotebookLastVisitService;
import com.lizhi.note.service.NotebookService;
import com.lizhi.note.service.NotepageService;
import jakarta.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Optional;

/**
 * 区别：
 * notebook : 笔记本
 * notepage： 笔记页
 */
@CrossOrigin(origins = "*", maxAge = 3600)
@RestController
@RequestMapping("/api/notebook")
public class NotebookController {
    @Autowired
    private NotebookService notebookService;

    @Autowired
    private NotepageService notepageService;

    @Autowired
    private NotebookLastVisitService notebookLastVisitService;

    @PostMapping
    public ResponseEntity<ApiResponse> createNotebook(@Valid @RequestBody NotebookDTO notebookDto) {
        NotebookDTO createdNotebook = notebookService.createNotebook(notebookDto);
        return ResponseUtil.success(createdNotebook);
    }

    @GetMapping("/{id}")
    public ResponseEntity<ApiResponse> getNotebook(@PathVariable Long id) {
        Optional<NotebookDTO> notebookDto = notebookService.getNotebookById(id);
        return notebookDto.map(dto -> ResponseUtil.success(dto))
                .orElseGet(() -> ResponseUtil.error(HttpStatus.NOT_FOUND.value(), "id对应笔记本没找到"));
    }

    @GetMapping
    public ResponseEntity<ApiResponse> getAllNotebooks() {
        List<NotebookDTO> notebooks = notebookService.getAllNotebooks();
        return ResponseUtil.success(notebooks);
    }

    @PutMapping("/{id}")
    public ResponseEntity<ApiResponse> updateNotebook(@PathVariable Long id, @Valid @RequestBody NotebookDTO notebookDto) {
        if (!id.equals(notebookDto.getId())) {
            return ResponseUtil.error(HttpStatus.BAD_REQUEST.value(), "bad request,id不匹配");
        }

        NotebookDTO updatedNotebook = notebookService.updateNotebook(notebookDto);
        return ResponseUtil.success(updatedNotebook);
    }

    @DeleteMapping("/{id}")
    public ResponseEntity<ApiResponse> deleteNotebook(@PathVariable Long id) {
        notebookService.deleteNotebook(id);
        return ResponseUtil.success(null,"执行成功");
    }

    @GetMapping("/pages/{notebookId}")
    public ResponseEntity<ApiResponse> getNotepagesByNotebookId(@PathVariable Long notebookId) {

        CustomUser user = getCurrentUserDetail();
        notebookLastVisitService.addLastVisitRecord(notebookId, user.getUserId());

        List<NotepageDTO> notepages = notepageService.getNotepagesByNotebookId(notebookId);
        return ResponseUtil.success(notepages);
    }

    public CustomUser getCurrentUserDetail(){
        UsernamePasswordAuthenticationToken authentication = (UsernamePasswordAuthenticationToken) SecurityContextHolder.getContext().getAuthentication();
        CustomUser user = (CustomUser) authentication.getPrincipal();
        return user;
    }
}
